#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>

using std::cin;
using std::cout;
using std::endl;
using std::unordered_map;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;

#define ERROR_CHECK(cond, msg, cleanup) \
    do{ \
        if(cond) { \
            std::cerr << "Error:" << msg << "(" << __FILE__ << ":" << __LINE__ << ")" << std::endl; \
            cleanup; \
            return; \
        } \
    }while(0)

class Dictionary{
public:
    void read_map(const std::string &filename);
    void convert_words(const std::string &filename);
private:
    bool is_word(const string&);
    unordered_map<string, string> _dict;
};

bool Dictionary::is_word(const string& word){
    
    for(auto& ch : word){
        if(!isalpha(ch)) return false;
    }

    return true;
}

void Dictionary::read_map(const std::string &filename){
    // 1. 打开文件
    ifstream ifs(filename);
    ERROR_CHECK(!ifs.good(), "ifstream is not good", ifs.close());

    // 2. 存放单词
    string line;
    string key, value;
    while(getline(ifs, line)){
        size_t pos = line.find(' ');
        key = line.substr(0, pos);
        value = line.substr(pos + 1);
        _dict[key] = value;
    }

    // 3. 关闭文件
    ifs.close();
}

void Dictionary::convert_words(const std::string &filename){
    // 1. 打开文件
    ifstream ifs(filename, std::ios::app);
    ERROR_CHECK(!ifs.good(), "ifs is not good", ifs.close());

    // 2. 遍历map
    string line;
    string key, value;
    while(getline(ifs, line)){
        istringstream iss(line);
        string word;
        while(iss >> word){
            auto it = _dict.find(word);
            if(it != _dict.end()){
                cout << it->second << " ";
            }
            else{
                cout << word << " ";
            }
        }
        cout << "\n";
    }

    ifs.close();
}

int main(){
    Dictionary dict;

    dict.read_map("map.txt");
    dict.convert_words("file.txt");
}
